package icu.javayanglei.bilibili.community.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.javayanglei.bilibili.community.service.UidMidService;
import icu.javayanglei.bilibili.domain.UidMid;
import icu.javayanglei.bilibili.mapper.UidMidMapper;
import icu.javayanglei.bilibili.util.CRCUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author yang
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UidMidServiceImpl extends ServiceImpl<UidMidMapper, UidMid> implements UidMidService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String getUID(String mid) {
        String result = "";
        final UidMid one = getOne(mid);

        if (ObjectUtil.isNotNull(one)) {
            result = one.getUid();
        } else {
            // 数据库没有，遍历
            long uid = getMaxUid();
            while (!result.equals(mid)) {
                uid++;
                result = CRCUtil.uidToMid(uid);
            }
            result = Convert.toStr(uid);
            final UidMid build = UidMid.builder()
                    .uid(Convert.toStr(result))
                    .mid(mid)
                    .build();
            log.debug("{}", build);
            this.saveOne(build);
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    void saveOne(UidMid uidMid) {
        this.save(uidMid);
    }

    @Override
    public Long getMaxUid() {
        final String uid = this.baseMapper.selectOne(new QueryWrapper<UidMid>().select("max(uid + 0) as uid")).getUid();
        return Convert.toLong(uid);
    }

    @Override
    public UidMid getOne(String mid) {
        return this.lambdaQuery().eq(UidMid::getMid, mid).one();
    }

}




